package com.example.socialmediaplatform.controller;

import com.example.socialmediaplatform.model.DAOUser;
import com.example.socialmediaplatform.model.UserDTO;
import com.example.socialmediaplatform.model.UserRepository;
import com.example.socialmediaplatform.model.Profile;
import com.example.socialmediaplatform.model.ProfileRepository;
import com.example.socialmediaplatform.model.ProfileDTO;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import javax.crypto.SecretKey;

import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProfileRepository profileRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value("${jwt.signing.key.secret}")
    private String jwtSecret;
    @Value("${jwt.token.expiration.in.seconds}")
    private long jwtExpiration;

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody UserDTO userDTO) {
        List<DAOUser> existing = userRepository.findByUsername(userDTO.getUsername());
        if (!existing.isEmpty()) {
            return ResponseEntity.badRequest().body("用户名已存在");
        }
        DAOUser user = new DAOUser();
        user.setUsername(userDTO.getUsername());
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        user.setEmail(userDTO.getEmail());
        userRepository.save(user);
        // 创建Profile
        Profile profile = new Profile();
        profile.setUsername(user.getUsername());
        profile.setEmail(user.getEmail());
        profile.setFirstname("");
        profile.setLastname("");
        profile.setAboutme(userDTO.getAboutme() != null ? userDTO.getAboutme() : "");
        profile.setAvatar("");
        profile.setBackground("");
        profile.setPhonenumber(userDTO.getPhonenumber() != null ? userDTO.getPhonenumber() : "");
        profile.setStudentnumber("");
        profileRepository.save(profile);
        // 注册成功后自动登录，返回JWT
        SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
        String token = Jwts.builder()
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpiration * 1000))
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
        Map<String, Object> result = new HashMap<>();
        result.put("message", "用户已创建");
        result.put("token", token);
        result.put("user", user);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody UserDTO userDTO) {
        List<DAOUser> users = userRepository.findByUsername(userDTO.getUsername());
        if (users.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "用户名不存在");
            return ResponseEntity.status(401).body(result);
        }
        DAOUser user = users.get(0);
        if (!passwordEncoder.matches(userDTO.getPassword(), user.getPassword())) {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "密码错误");
            return ResponseEntity.status(401).body(result);
        }
        SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
        String token = Jwts.builder()
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpiration * 1000))
                .signWith(key, SignatureAlgorithm.HS512)
                .compact();
        Map<String, Object> result = new HashMap<>();
        result.put("message", "登录成功");
        result.put("token", token);
        result.put("user", user);
        return ResponseEntity.ok(result);
    }
} 
